<template>
  <div class="picture-list">
    <!-- 图片列表 - 极简风格 -->
    <div v-if="loading" class="loading-container-minimal">
      <a-spin size="large" />
    </div>
    
    <div v-else-if="!dataList || dataList.length === 0" class="empty-container-minimal">
      <div class="empty-content-minimal">
        <p class="empty-text-minimal">暂无图片</p>
      </div>
    </div>
    
    <div v-else-if="dataList && dataList.length > 0" class="grid-container">
      <div 
        v-for="(picture, index) in dataList" 
        :key="picture.id"
        class="grid-item"
        @click="doClickPicture(picture)"
        
      >
        <div class="image-container">
          <img
            :alt="picture.name"
            :src="`${picture.thumbnailUrl ?? picture.url}?w=50&h=50&blur=10`"
            class="low-res-image"
            loading="lazy"
          />
          <img
            :alt="picture.name"
            :src="picture.thumbnailUrl ?? picture.url"
            class="grid-image"
            loading="lazy"
            @load="onImageLoad($event, picture)"
          />
        </div>
        <div class="masonry-overlay" v-if="showOp">
          <div class="masonry-actions" @click.stop>
            <a-button 
              type="text" 
              size="small" 
              @click="(e) => doShare(picture, e)"
              class="action-btn-masonry"
            >
              <ShareAltOutlined />
            </a-button>
            <a-button 
              type="text" 
              size="small" 
              @click="(e) => doSearch(picture, e)"
              class="action-btn-masonry"
            >
              <SearchOutlined />
            </a-button>
            <a-button 
              v-if="canEdit"
              type="text" 
              size="small" 
              @click="(e) => doEdit(picture, e)"
              class="action-btn-masonry"
            >
              <EditOutlined />
            </a-button>
            <a-button 
              v-if="canDelete"
              type="text" 
              size="small" 
              @click="(e) => doDelete(picture, e)"
              class="action-btn-masonry delete-btn-masonry"
            >
              <DeleteOutlined />
            </a-button>
          </div>
        </div>
      </div>
    </div>
    
    <ShareModal ref="shareModalRef" :link="shareLink" />
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import {
  DeleteOutlined,
  EditOutlined,
  SearchOutlined,
  ShareAltOutlined,
} from '@ant-design/icons-vue'
import { deletePictureUsingPost } from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import ShareModal from '@/components/ShareModal.vue'
import { ref, watch } from 'vue'

interface Props {
  dataList?: API.PictureVO[]
  loading?: boolean
  showOp?: boolean
  canEdit?: boolean
  canDelete?: boolean
  onReload?: () => void
}

const props = withDefaults(defineProps<Props>(), {
  dataList: () => [],
  loading: false,
  showOp: false,
  canEdit: false,
  canDelete: false,
})

watch(() => props.dataList, (newList) => {
  if (newList && newList.length > 0) {
    imageDimensions.value.clear()
  }
}, { deep: true })

const imageDimensions = ref(new Map<string | number, { w: number; h: number }>())

const onImageLoad = (event: Event, picture: API.PictureVO) => {
  const img = event.target as HTMLImageElement
  if (img.naturalWidth > 0 && img.naturalHeight > 0) {
    imageDimensions.value.set(picture.id, { w: img.naturalWidth, h: img.naturalHeight })
    // 添加loaded类，使高分辨率图片可见
    img.classList.add('loaded')
  }
}

const router = useRouter()
// 跳转至图片详情页
const doClickPicture = (picture: API.PictureVO) => {
  router.push({
    path: `/picture/${picture.id}`,
  })
}

// 搜索
const doSearch = (picture, e) => {
  // 阻止冒泡
  e.stopPropagation()
  // 打开新的页面
  window.open(`/search_picture?pictureId=${picture.id}`)
}

// 编辑
const doEdit = (picture, e) => {
  // 阻止冒泡
  e.stopPropagation()
  // 跳转时一定要携带 spaceId
  router.push({
    path: '/add_picture',
    query: {
      id: picture.id,
      spaceId: picture.spaceId?.toString(),
    },
  })
}

// 删除数据
const doDelete = async (picture, e) => {
  // 阻止冒泡
  e.stopPropagation()
  const id = picture.id
  if (!id) {
    return
  }
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    props.onReload?.()
  } else {
    message.error('删除失败')
  }
}

// ----- 分享操作 ----
const shareModalRef = ref()
// 分享链接
const shareLink = ref<string>()
// 分享
const doShare = (picture, e) => {
  // 阻止冒泡
  e.stopPropagation()
  shareLink.value = `${window.location.protocol}//${window.location.host}/picture/${picture.id}`
  if (shareModalRef.value) {
    shareModalRef.value.openModal()
  }
}
</script>

<style scoped>
.picture-list {
  padding: 0;
}

/* 加载状态 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

/* 空状态 */
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  padding: 40px;
}

.empty-content {
  text-align: center;
  color: #999999;
}

.empty-icon {
  width: 120px;
  height: 120px;
  margin-bottom: 24px;
  opacity: 0.3;
  color: #999999;
}

.empty-text {
  font-size: 18px;
  font-weight: 500;
  color: #666666;
  margin: 0 0 8px;
}

.empty-subtitle {
  font-size: 14px;
  color: #999999;
  margin: 0;
}

/* 图片网格 - 简约风格 */
.picture-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  padding: 0;
}

.picture-item {
  cursor: pointer;
  transition: all 0.3s ease;
}

.picture-card {
  background: #ffffff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
}

.picture-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  border-color: #e0e0e0;
}

.picture-image-container {
  position: relative;
  width: 100%;
  height: 240px;
  overflow: hidden;
  background: #f5f5f5;
}

.picture-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.picture-card:hover .picture-image {
  transform: scale(1.05);
}

.picture-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  opacity: 0;
  transition: opacity 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.picture-card:hover .picture-overlay {
  opacity: 1;
}

.picture-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.action-btn {
  background: rgba(255, 255, 255, 0.9);
  border: none;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  color: #333333;
}

.action-btn:hover {
  background: #ffffff;
  transform: scale(1.1);
  color: #000000;
}

.action-btn.delete-btn:hover {
  color: #ff4d4f;
}

/* 图片信息 */
.picture-info {
  padding: 20px;
}

.picture-title {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 12px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.picture-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.category-tag {
  background: #f5f5f5;
  border: 1px solid #e0e0e0;
  color: #666666;
  font-size: 12px;
  font-weight: 500;
  border-radius: 4px;
  padding: 2px 8px;
}

.picture-tags {
  display: flex;
  align-items: center;
  gap: 6px;
  flex: 1;
  overflow: hidden;
}

.tag-text {
  font-size: 12px;
  color: #999999;
  font-weight: 500;
}

.tag-more {
  font-size: 12px;
  color: #cccccc;
  font-weight: 500;
}

/* 瀑布流布局样式 - 重新设计 */
.masonry-container {
  margin: 0 auto;
  padding: 4px;
  background: #ffffff;
}

.masonry-item {
  cursor: pointer;
  transition: all 0.3s ease;
  background: #ffffff;
  position: relative;
  overflow: hidden;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  margin-bottom: 10px;
}

.masonry-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.masonry-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
  background: #f8f8f8;
  display: block;
}

.masonry-item:hover .masonry-image {
  transform: scale(1.02);
}

.masonry-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  opacity: 0;
  transition: opacity 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.masonry-item:hover .masonry-overlay {
  opacity: 1;
}

.masonry-actions {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}

.action-btn-masonry {
  background: rgba(255, 255, 255, 0.95);
  border: none;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  color: #333333;
  backdrop-filter: blur(4px);
}

.action-btn-masonry:hover {
  background: #ffffff;
  transform: scale(1.1);
  color: #000000;
}

.action-btn-masonry.delete-btn-masonry:hover {
  color: #ff4d4f;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
  padding: 20px;
  margin: 0 auto;
  max-width: 1400px;
  justify-items: center;
}

.grid-item {
  position: relative;
  overflow: hidden;
  border-radius: 12px;
  background-color: #f0f0f0;
  aspect-ratio: 3 / 4;
  width: 100%;
  max-width: 250px;
  transition: transform 0.3s ease;
}

.grid-item:hover {
  transform: scale(1.05);
}

.image-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 确保图片在容器中居中显示 */
.low-res-image,
.grid-image {
  object-fit: contain;
}

.low-res-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  filter: blur(2px);
  transition: opacity 0.3s ease;
  z-index: 1;
}

.grid-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  transition: transform 0.3s ease, opacity 0.5s ease;
  opacity: 0;
  z-index: 2;
}

.grid-image.loaded {
  opacity: 1;
}

.grid-item:hover .grid-image {
  transform: scale(1.02);
}

@media (max-width: 1200px) {
  .grid-container {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 992px) {
  .grid-container {
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    padding: 16px;
  }
  
  .grid-item {
    max-width: 220px;
  }
}

@media (max-width: 768px) {
  .grid-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
    padding: 12px;
  }
  
  .grid-item {
    max-width: 180px;
  }
}

@media (max-width: 480px) {
  .grid-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    padding: 10px;
  }
  
  .grid-item {
    max-width: 150px;
  }
}
</style>
onMounted(() => {
  updateItemWidth()
  if (masonryContainer.value) {
    masonryInstance = new Masonry(masonryContainer.value, {
      itemSelector: '.masonry-item',
      columnWidth: itemWidth.value,
      gutter: 10,
      percentPosition: false,
      fitWidth: true,
    })
    nextTick(() => {
      masonryInstance?.reloadItems()
      masonryInstance?.layout()
    })
  }
  const onResize = () => {
    updateItemWidth()
    nextTick(() => {
      masonryInstance?.layout()
    })
  }
  window.addEventListener('resize', onResize)
  onBeforeUnmount(() => {
    window.removeEventListener('resize', onResize)
    masonryInstance?.destroy()
    masonryInstance = null
  })
})
